/**
 * Created by wangguoqing on 2017/12/29.
 */

var shStatus = new Array("<sapn style='color:red;'>禁用</span>", "启用");
var params = new Object();
var noPerFlag = false;
var subOrgFlag = false;
var orgFlag = false;
var url = path + "/system/user/list";

$(function () {
    //设置AjaxLoading
    setAjaxLoading();
    //初始化角色
    initRole();
    orgFlag=true;
    ajaxJson(path + '/system/org/getDirectChildrenTreeData', null, singleInitTreeExtend);

    var grid = $("#tt");
    initGrid(grid);

    $("#tt").datagrid({
        //双击事件
        onDblClickRow: function (index, row) {
            btnEditNodeByGrid();
        }
    });
});

/**
 * 初始化表格和数据
 */
function initGrid(grid) {
    var columns = [
        {
            field: "userId", title: "ID", hidden: true,
            align: "left", sortable: false, resizable: true, width: 120
        },
        {
            field: "userCode",
            title: "登录账号",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 100
        },
        {
            field: "userName",
            title: "姓名",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "phoneNo",
            title: "手机号码",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 100
        },
        {
            field: "email",
            title: "邮箱",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 140
        },
        {
            field: "validMark",
            title: "状态",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80,
            formatter: function (value, row, index) {
                return shStatus[value];
            }
        },
        {
            field: "orgCode",
            title: "机构编码",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 100
        },
        {
            field: "orgName",
            title: "机构名称",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 300
        },
        {
            field: "roleDtos",
            title: "角色",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 280,
            formatter: function (value, row, index) {
                var js = "";
                $.each(row.roleDtos, function (index, val) {
                    if (index == 0) {
                        js += val.roleName;
                    } else {
                        js += "，" + val.roleName;
                    }
                });
                return js;
            }
        }
    ];
    setParamsFlag();
    initPageGrid(grid, params, url, columns, "#tb");
}
/**
 * 初始化角色
 */
function initRole() {
    $.ajax({
        type : "POST",                                            // 使用post方法访问后台
        dataType : "json",                                        // 返回json格式的数据
        url: path+'/system/user/initRole',                         // 要访问的后台地址
        complete : function() {},
        success : function(result) {// result为返回的数据
            if(result.code=='0000'){
                result.returnObject.rows.unshift({
                    'roleId': '',
                    'roleName': '--请选择--'
                });//向json数组开头添加自定义数据
                $('#initRole').combobox({
                    data : result.returnObject.rows,
                    valueField:'roleId',
                    textField:'roleName',
                    multiple: false,
                    editable:false,
                    panelHeight: 'auto',
                    onLoadSuccess: function () { //加载完成后,设置选中第一项
                        var val = $("#initRole").combobox('getData');
                        for (var item in val[0]) {
                            if (item == 'ID') {
                                $("#initRole").combobox('select', val[0][item]);
                            }
                        }
                    }
                });
            }

            $("#initRole").combobox("setValue", "");
        }
    });
}

/**
 * 查询按钮
 */
function btnQuery() {
    params.userName = $("#userNameQuery").val();
    params.validMark = $("#validMarkQuery").combobox("getValue");
    params.roleId = $("#initRole").combobox("getValue");
    params.userCode = $("#userCodeQuery").val();
    setParamsFlag();
    var grid = $("#tt");
    changePage(grid, params, url);
    getPage(grid, params, url);
}

/**
 * 查询机构
 */
function btnQueryOrg() {
    var orgParams = new Object();
    params.orgName = $("#orgName").val();
    orgParams.orgName = $("#orgName").val();
    if (orgFlag) {
        if (params.orgName) {
            ajaxJson(path+'/system/org/getTreeData',orgParams,initTree);
        } else {
            ajaxJson(path+'/system/org/getDirectChildrenTreeData', null, singleInitTree);
        }
    }
}

/**
 * 重置
 */
function btnReset() {
    $("#userNameQuery").val("");
    $("#userCodeQuery").val("");
    $("#validMarkQuery").combobox("setValue","");
    $("#initRole").combobox("setValue","");
    btnQuery();
}

/**
 * 设置传入值Params的flag
 */
function setParamsFlag() {
    selectAssignPermissions();
    selectsubIncluding();
    params.noPerFlag = noPerFlag;
    params.subOrgFlag = subOrgFlag;
    params.orgFlag = orgFlag;
}

/**
 * 未分配权限人员 checkbox选中事件
 */
function selectAssignPermissions() {
    if ($('#noAssignPermissions').is(':checked')) {
        $("#subIncluding").removeAttr("checked");
        noPerFlag = true;
        subOrgFlag = false;
        orgFlag = false;
    } else {
        noPerFlag = false;
        orgFlag = true;
    }
}

/**
 * 是否包含下级机构人员 checkbox选中事件
 */
function selectsubIncluding() {

    if ($('#subIncluding').is(':checked')) {
        $("#noAssignPermissions").removeAttr("checked");
        subOrgFlag = true;
        orgFlag = true;
        noPerFlag = false;
    } else {
        subOrgFlag = false;
    }

}

/**
 * 增加人员
 */
function btnAddNode() {
    layer.open({
        type: 2,
        title: ['系统用户 - 添加', 'background: #38acff;'],
        shadeClose: false,
        shade: 0.3,
        area: ['710px', '530px'],
        content: path + '/system/user/toAdd' //iframe的url
    });
}
/**
 *  修改人员
 */
function btnEditNodeByGrid() {
    var rows = $('#tt').datagrid('getSelections');
    if (rows.length == 0) {
        $.messager.alert("操作提示", "请选一个系统用户！", "info");
        return;
    }
    layer.open({
        type: 2,
        title: ['系统用户 - 修改', 'background: #38acff;'],
        shadeClose: true,
        shade: 0.3,
        area: ['710px', '530px'],
        content: path + '/system/user/toUpdate' //iframe的url
    });
}
/**
 * 删除人员
 */
function btnDelNodeByGrid() {
    var rows = $('#tt').datagrid('getSelections');
    if (rows.length == 0) {
        $.messager.alert("操作提示", "请选一个系统用户！", "warning");
        return;
    }
    var rowData = rows[0];
    var param = new Object();
    param.userId = rowData.userId;
    $.messager.alert("操作提示", "是否要删除选中的用户?","confirm", function () {

            $.ajax({
                type: "POST",
                url: path + '/system/user/delete',
                data: param,
                dataType: "json",
                async: false,
                success: function callback(data) {
                    var analyMsg = data;
                    if (analyMsg.code != "0000") {
                        $.messager.alert('操作提示', analyMsg.msg, 'error', function () {
                        });
                    } else {
                        $.messager.alert('操作提示', "删除成功", 'info', function () {
                        });
                        btnQuery();
                    }
                },
                error: function (data, textstatus) {
                    $.messager.alert('操作提示', data.responseText, 'error', function () {
                    });
                }
            });

    });
}

/**
 * 密码重置
 */
function btnBackPwdByGrid() {
    var rows = $('#tt').datagrid('getSelections');
    if (rows.length == 0) {
        $.messager.alert("操作提示", "请先选中要重置密码的用户。", "warning");
        return;
    }
    var rowData = rows[0];
    var param = new Object();
    param.userId = rowData.userId;
    $.messager.alert("操作提示", "是否重置用户密码为111111？","confirm", function () {

            $.ajax({
                type: "POST",
                url: path + '/system/user/backPwd',
                data: param,
                dataType: "json",
                async: false,
                success: function callback(data) {
                    var analyMsg = data;
                    if (analyMsg.code != "0000") {
                        $.messager.alert('操作提示', analyMsg.msg, 'error', function () {
                        });
                    } else {
                        $.messager.alert('操作提示', "重置成功！", 'info', function () {
                        });
                        btnQuery();
                    }
                },
                error: function (data, textstatus) {
                    $.messager.alert('操作提示', data.responseText, 'error', function () {
                    });
                }
            });

    });
}

/**
 * 启用禁用用户
 */
function btnYxbzNodeByGrid() {
    var rows = $('#tt').datagrid('getSelections');
    if (rows.length == 0) {
        $.messager.alert("操作提示", "请先选中要启用/禁用的用户。", "warning");
    }
    var rowData = rows[0];
    var param = new Object();
    param.userId = rowData.userId;
    param.validMark = rowData.validMark;
    var mess = "";
    if (param.validMark == "1") {
        mess = "禁用后该用户将无法登陆，是否禁用?";
        param.validMark = "0";
    } else {
        mess = "是否启用?";
        param.validMark = "1";
    }
    $.messager.alert("操作提示", mess,"confirm", function (b) {

            $.ajax({
                type: "POST",
                url: path + '/system/user/updateValidMark',
                data: param,
                dataType: "json",
                async: false,
                success: function callback(data) {
                    var analyMsg = data;
                    if (analyMsg.code != "0000") {
                        $.messager.alert('操作提示', analyMsg.msg, 'error', function () {
                        });
                    } else {
                        $.messager.alert('操作提示', "操作成功。", 'info', function () {
                        });
                        btnQuery();
                    }
                },
                error: function (data, textstatus) {
                    $.messager.alert('操作提示', data.responseText, 'error', function () {
                    });
                }
            });
    });
}
/**导出为 Excel */
function btnExport() {
    var exportUrl =path+ '/system/user/exportData';
    $("#exportForm").attr("action", exportUrl);
    //清空表单
    $("#exportForm").html("");
    //将json数据转为form表单形式
    $.each(params, function (i, obj) {
        $("#exportForm").append("<input  type='hidden' name='" + i + "' value='" + obj + "' />");
    });
    $("#exportForm").submit();

}

/**导入为 Excel */
function btnImport(attachmentParamterId) {

    if (attachmentParamterId == "" || attachmentParamterId == null) {
        return $.alert("default", "info", "未获取到当前页面的附件参数id");
    }
    var url = '/common/importExcel/importExcel?attachmentParamterId=' + attachmentParamterId;
    top.layer.open({
        type: 2,
        title: '系统用户信息 - Excel导入',
        shadeClose: false,
        shade: 0.3,
        area: ['500px', '250px'],
        content: url,
        maxmin: false,
        end: function(){
            btnQuery();
        }
    });
}

/**
 * 初始化树点击函数
 * @param event
 * @param treeId
 * @param treeNode
 */
function zTreeOnClick(event, treeId, treeNode) {
    params.pid = treeNode.id;
    if (!treeNode.pIds) {
        treeNode.pIds = "";
    }
    params.pcode = treeNode.code;
    params.orgCode = treeNode.code;
    treeSingleLoad(params, treeId, treeNode);//调用层级加载树的方法
    btnQuery();

}

/**
 *展开树调用方法
 */
function zTreeOnExpand(event, treeId, treeNode) {
    params.orgCode = treeNode.code;
    treeSingleLoad(params, treeId, treeNode)
}

/**
 * 树层级加载方法
 */
function treeSingleLoad(params, treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("tree");
    var node = treeNode;
    //没有子节点才去查询
    if (node.children == null || node.children == "undefined") {
        $.ajax({
            type: "POST",
            async: true,
            url: path + "/system/org/getDirectChildrenTreeData",
            data: params,
            dataType: "json",
            success: function (data) {
                var analyMsg = data;
                analyMsg.code == "0000"
                if (analyMsg.code == "0000") {
                    //添加新节点
                    var newNode = treeObj.addNodes(node, data.returnObject);
                }
            },
            error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                $.alert("default", "error", data.responseText);
            }
        });
    }
}